package com.example.daily.demo.config;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import javax.mail.internet.MimeUtility;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

/**
 * 发送邮件配置类
 * @author tianzehua
 * @date 2020/11/11
 */
@Configuration
public class SendMailSmtp {
        @Value("${mail.login.username}")
        private String mailUsername;
        @Value("${mail.login.password}")
        private String mailPassword;

        public  void sendHtmlMail(String[] to, String subject,String text) {
             try{
                     //to 接收邮箱
                     String from = mailUsername;//发件人昵称展示   *
                     String host = "smtp.qiye.163.com";//163企业邮箱smtp   *
                     String username = mailUsername;//企业邮箱   *
                     String password= mailPassword;//企业邮箱密码   *

                     //设置服务器验证信息
                     Properties prop = new Properties();
                     prop.setProperty("mail.smtp.auth", "true");
                     prop.setProperty("mail.smtp.timeout", "7200000"); // 加密端口(ssl)  可通过 https://qiye.163.com/help/client-profile.html 进行查询

                     MailSSLSocketFactory sf = new MailSSLSocketFactory();// SSL加密
                     sf.setTrustAllHosts(true); // 设置信任所有的主机
                     prop.put("mail.smtp.ssl.enable", "true");
                     prop.put("mail.smtp.ssl.socketFactory", sf);

                     //设置邮件内容
                     JavaMailSenderImpl javaMailSend = new JavaMailSenderImpl();
                     MimeMessage message = javaMailSend.createMimeMessage();
                     MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, "utf-8");
                     String nick = MimeUtility.encodeText(from);//设置昵称
                     messageHelper.setFrom(new InternetAddress(nick + " <"+username+">"));// 邮件发送者
                     messageHelper.setTo(to);
                     messageHelper.setSubject(subject);
                     messageHelper.setText(text, true);

                     //设置邮件服务器登录信息
                     javaMailSend.setHost(host);
                     javaMailSend.setUsername(username);
                     javaMailSend.setPassword(password);
                     javaMailSend.setJavaMailProperties(prop);
                    // System.out.println("maillText：" + text);
                     javaMailSend.send(message);
                 } catch (Exception e) {
                     System.out.println(e);
                     e.printStackTrace();
                 }
         }

}

